
package com.nikmesoft.android.alwaysontime.activities;

import java.util.ArrayList;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;

@SuppressWarnings("deprecation")
public class TabGroupActivity extends ActivityGroup
{	private ArrayList<String> mIdList;
	private LocalActivityManager manager;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{	super.onCreate(savedInstanceState);
		if (mIdList == null)
			mIdList = new ArrayList<String>();
		manager = getLocalActivityManager();
	}

	@Override
	public void finishFromChild(Activity child)
	{	// get size
		int index = mIdList.size() - 1;
		// if size < 1 then finish all
		if (index < 1)
		{	finish();
			return;
		}
		// remove activity on top
		manager.destroyActivity(mIdList.get(index), true);
		// remove from list
		mIdList.remove(index);
		index--;
		String lastId = mIdList.get(index);
		Intent lastIntent = manager.getActivity(lastId).getIntent();
		Window newWindow = manager.startActivity(lastId, lastIntent);
		setContentView(newWindow.getDecorView());
	}

	// start new child activity in group
	public void startChildActivity(String id, Intent intent)
	{	Window window = getLocalActivityManager().startActivity(id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		if (window != null)
		{	mIdList.add(id);
			setContentView(window.getDecorView());
		}
	}

	// handle back key
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{	if (keyCode == KeyEvent.KEYCODE_BACK) { return true; }
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event)
	{	if (keyCode == KeyEvent.KEYCODE_BACK)
		{	onBackPressed();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	public void onBackPressed()
	{	int length = mIdList.size();
		if (length > 1)
		{	Activity current = getLocalActivityManager().getActivity(mIdList.get(length - 1));
			current.finish();
		}
		else
		{	super.onBackPressed();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{	Activity topActivity = getLocalActivityManager().getActivity(mIdList.get(mIdList.size() - 1));
		if (topActivity.getClass().getSuperclass().getName().equals(BaseActivity.class.getName()))
		{	((BaseActivity) topActivity).onGroupActivityResult(requestCode, resultCode, data);
		}
	}
}
